package com.order.api.util;


import com.order.api.constant.ThreadLocalKeyEnum;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程内部数据工具类
 */
@Component
public class ThreadLocalUtil {
    private final ThreadLocal<Map<String,Object>> store = ThreadLocal.withInitial(HashMap::new);

    public Object get(String key){
        Map<String,Object> map= store.get();
        return map.getOrDefault(key,null);
    }
    public void put(String key,Object obj){
        store.get().put(key, obj);
    }
    public void setUserId(Long userId){
        put(ThreadLocalKeyEnum.USERID.getKey(),userId);
    }

    /**
     * 获取当前线程用户的userId
     */
    public Long getUserId(){
        Object obj = get(ThreadLocalKeyEnum.USERID.getKey());
        return obj != null ? Long.parseLong(obj.toString()) : null;
    }
    public void setToken(String token){
        put(ThreadLocalKeyEnum.TOKEN.getKey(), token);
    }
    /**
     * 获取当前线程用户的token
     */
    public String getToken(){
        Object obj = get(ThreadLocalKeyEnum.TOKEN.getKey());
        return obj !=null ? obj.toString() : "" ;
    }


}
